
// 获取投稿按钮和模态框
const uploadBtn = document.getElementById('uploadBtn');
const uploadModal = document.getElementById('uploadModal');
const closeBtn = document.querySelector('.close-btn');

// 打开投稿模态框
uploadBtn.addEventListener('click', function () {
    uploadModal.style.display = 'flex';
    document.body.style.overflow = 'hidden'; // 防止背景滚动
});

// 关闭投稿模态框
closeBtn.addEventListener('click', function () {
    uploadModal.style.display = 'none';
    document.body.style.overflow = 'auto'; // 恢复滚动
});

// 点击模态框外部关闭
window.addEventListener('click', function (event) {
    if (event.target === uploadModal) {
        uploadModal.style.display = 'none';
        document.body.style.overflow = 'auto'; // 恢复滚动
    }
});

// 文件上传区域交互效果
const fileUploads = document.querySelectorAll('.file-upload');
fileUploads.forEach(upload => {
    upload.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.style.borderColor = '#00A1D6';
        this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
    });

    upload.addEventListener('dragleave', function () {
        this.style.borderColor = '';
        this.style.backgroundColor = '';
    });

    upload.addEventListener('drop', function (e) {
        e.preventDefault();
        this.style.borderColor = '';
        this.style.backgroundColor = '';

        if (e.dataTransfer.files.length) {
            // 这里处理文件上传逻辑
            this.innerHTML = `<i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                                      <p>${e.dataTransfer.files[0].name}</p>
                                      <p class="small" style="color:#4CAF50;">上传成功</p>`;
        }
    });

    upload.addEventListener('click', function () {
        // 模拟文件选择器
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = this.id === 'videoUpload' ? 'video/*' : 'image/*';
        input.click();

        input.addEventListener('change', function () {
            if (this.files.length) {
                upload.innerHTML = `<i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                                          <p>${this.files[0].name}</p>
                                          <p class="small" style="color:#4CAF50;">上传成功</p>`;
            }
        });
    });
});

// 添加导航项点击效果
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
    item.addEventListener('click', function (e) {
        //e.preventDefault();
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');

        // 更新页面标题
        const title = this.querySelector('span').textContent;
        document.querySelector('.section-title').innerHTML =
            `<i class="${this.querySelector('i').className}"></i> ${title}`;
    });
});

// 图表数据点悬停效果
document.querySelectorAll('.data-point').forEach(point => {
    point.addEventListener('mouseenter', function () {
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = this.getAttribute('data-value');
        tooltip.style.position = 'absolute';
        tooltip.style.background = 'rgba(0,0,0,0.8)';
        tooltip.style.color = 'white';
        tooltip.style.padding = '5px 10px';
        tooltip.style.borderRadius = '4px';
        tooltip.style.zIndex = '100';

        const rect = this.getBoundingClientRect();
        tooltip.style.left = `${rect.left}px`;
        tooltip.style.top = `${rect.top - 30}px`;

        document.body.appendChild(tooltip);

        this.tooltip = tooltip;
    });

    point.addEventListener('mouseleave', function () {
        if (this.tooltip) {
            this.tooltip.remove();
            this.tooltip = null;
        }
    });
});








//ajax

document.addEventListener('DOMContentLoaded', function () {
    let timeRangeSelect = document.getElementById('timeRange');//时间
    let dataTypeSelect = document.getElementById('dataType');//类型
    let videoCategorySelect = document.getElementById('videoCategory');//视频
    // 初始加载数据
    loadChartData(timeRangeSelect.value || "月", dataTypeSelect.value || "all", videoCategorySelect.value || "all");
    timeRangeSelect.addEventListener('change', function () {
        loadChartData(timeRangeSelect.value, dataTypeSelect.value, videoCategorySelect.value);
    });
    dataTypeSelect.addEventListener('change', function () {
        loadChartData(timeRangeSelect.value, dataTypeSelect.value, videoCategorySelect.value);
    });
    videoCategorySelect.addEventListener('change', function () {
        loadChartData(timeRangeSelect.value, dataTypeSelect.value, videoCategorySelect.value);
    });
});

// 加载图表数据
function loadChartData(timeRange, dataType, category) {
	let statVideo = document.getElementById('statVideo').textContent||'0';//累计播放量
    let statFen = document.getElementById('statFen').textContent||'0';//粉丝数量
    let statDay = 0//昨日播放
    // 发送AJAX请求
    $.ajax({
        url: "dataCenter.do",
        type: "GET",
        data: {
            timeRange: timeRange,
            dataType: dataType,
            category: category,
            statVideo:statVideo,
            statFen:statFen,
            statDay:statDay
        },
        success: function (data) {
            // 处理返回的数据并更新图表
            updateCharts(data,dataType);
            updateCount(data);
        }
    });
}
// 更新图表数据
function updateCharts(data,dataType) {
    let chartsContainer = document.querySelector('.charts-container');
    chartsContainer.innerHTML = '';
    // 生成各个表格
    if(dataType=="all"){
    	chartsContainer.appendChild(createPlayTrendTable(data.playTrend));
        chartsContainer.appendChild(createFanGrowthTable(data.fanGrowthTrend));
        chartsContainer.appendChild(createGenderDistributionTable(data.genderDistribution));
        chartsContainer.appendChild(createAgeDistributionTable(data.ageDistribution));
        chartsContainer.appendChild(createDetailedDataTable(data.detailedData));
    }else if(dataType=="play"){
    	chartsContainer.appendChild(createPlayTrendTable(data.playTrend));
    	chartsContainer.appendChild(createDetailedDataTable(data.detailedData));
    }else if(dataType=="fan"){
    	chartsContainer.appendChild(createFanGrowthTable(data.fanGrowthTrend));
        chartsContainer.appendChild(createGenderDistributionTable(data.genderDistribution));
        chartsContainer.appendChild(createAgeDistributionTable(data.ageDistribution));
    }
    // 添加淡入动画效果
    let tables = chartsContainer.querySelectorAll('.chart-card');
    tables.forEach((table, index) => {
        table.style.opacity = '0';
        table.style.transform = 'translateY(20px)';
        table.style.transition = 'opacity 0.5s ease, transform 0.5s ease';

        setTimeout(() => {
            table.style.opacity = '1';
            table.style.transform = 'translateY(0)';
        }, 100 * index);
    });
}
//累计播放量 粉丝数
function updateCount(data) {
	console.log(data);
    let statVideoElement = document.getElementById('statVideo');
    let statFenElement = document.getElementById('statFen');
    if (statVideoElement) {
        statVideoElement.textContent = formatNumber(data.totalPlayCount);
    } else {
        let parentContainer = document.querySelector('.stats-cards');
        if (parentContainer) {
            parentContainer.appendChild(createPlayCountCard(data.totalPlayCount));
        }
    }
    if (statFenElement) {
        statFenElement.textContent = formatNumber(data.fanCount);
    } else {
        let parentContainer = document.querySelector('.stats-cards');
        if (parentContainer) {
            parentContainer.appendChild(createFanCountCard(data.fanCount));
        }
    }
}

// 格式化数字的函数
function formatNumber(num) {
    // 确保处理数字类型
    if (typeof num !== 'number') {
        num = parseFloat(num) || 0;
    }
    // 使用千位分隔符格式化数字
    return num.toLocaleString();
}

// 更新前端
function createPlayCountCard(playCount) {
    let card = document.createElement('div');
    card.className = 'stat-card';
    card.innerHTML = `
        <div class="stat-title">累计播放量</div>
        <div class="stat-value">${formatNumber(playCount)}</div>
        <div class="stat-change">↑ 12.5% 较上周</div>
    `;
    return card;
}

function createFanCountCard(fanCount) {
    let card = document.createElement('div');
    card.className = 'stat-card';
    card.innerHTML = `
        <div class="stat-title">粉丝总数</div>
        <div class="stat-value">${formatNumber(fanCount)}</div>
        <div class="stat-change">↑ 356 较上周</div>
    `;
    return card;
}
function createFanCountCard(fanCount) {
    let card = document.createElement('div');
    card.className = 'stat-card';
    card.innerHTML = `
        <div class="stat-title">粉丝总数</div>
        <div class="stat-value">${formatNumber(fanCount)}</div>
        <div class="stat-change">↑ 356 较上周</div>
    `;
    return card;
}

//创建播放趋势表格
function createPlayTrendTable(dataArray) {
    let table = document.createElement('div');
    table.className = 'chart-card';
    // 构建表格基本结构
    let tableHTML = `
        <div class="chart-header">
            <div class="chart-title">播放量趋势</div>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>日期</th>
                    <th>播放量</th>
                </tr>
            </thead>
            <tbody>
    `;
    // 检查数据是否存在
    if (dataArray && dataArray.length > 0) {
        // 遍历数组生成表格行
        dataArray.forEach(item => {
        	let date = new Date(item.date);//返回后端日期并自动转换成yy-dd
            let month = (date.getMonth() + 1).toString().padStart(2, '0');
            let day = date.getDate().toString().padStart(2, '0');
            let formattedDate = `${month}-${day}`;

            // 获取播放量（使用正确的属性名 playCount）
            let playCount = item.playCount.toLocaleString();

            // 添加表格行
            tableHTML += `
                <tr>
                    <td>${formattedDate}</td>
                    <td>${playCount}</td>
                </tr>
            `;
        });
    } else {
        // 数据为空时显示提示
        tableHTML += `
            <tr>
                <td colspan="2" class="empty-data">暂无数据</td>
            </tr>
        `;
    }
    // 完成表格结构
    tableHTML += `
            </tbody>
        </table>
    `;
    table.innerHTML = tableHTML;
    return table;
}
//粉丝记录表
function createFanGrowthTable(dataArray) {
	let table = document.createElement('div');
    table.className = 'chart-card';
    // 初始化表格结构
    let tableHTML = `
        <div class="chart-header">
            <div class="chart-title">粉丝增长趋势</div>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>日期</th>
                    <th>新增粉丝</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 检查数据是否存在
    if (dataArray && dataArray.length > 0) {
        // 遍历数据生成表格行
        dataArray.forEach(item => {
            // 格式化日期（从 "YYYY-MM-DD" 转为 "MM-DD"）
        	let date = new Date(item.date);
        	let month = (date.getMonth() + 1).toString().padStart(2, '0');
        	let day = date.getDate().toString().padStart(2, '0');
        	let formattedDate = `${month}-${day}`;
            
            // 获取新增粉丝数（添加安全检查）
        	let newFans = (item.newFans || 0).toLocaleString();
            
            // 添加表格行
            tableHTML += `
                <tr>
                    <td>${formattedDate}</td>
                    <td>${newFans}</td>
                </tr>
            `;
        });
    } else {
        // 数据为空时显示空状态
        tableHTML += `
            <tr>
                <td colspan="2" class="empty-data">暂无数据</td>
            </tr>
        `;
    }
    
    // 完成表格结构
    tableHTML += `
            </tbody>
        </table>
    `;
    
    table.innerHTML = tableHTML;
    return table;
}
//性别
function createGenderDistributionTable(dataList) {
	let table = document.createElement('div');
    table.className = 'chart-card';
    // 检查数据是否存在
    if (!dataList || dataList.length === 0) {
        table.innerHTML = `
            <div class="chart-header">
                <div class="chart-title">观众性别分布</div>
            </div>
            <div class="empty-data">
                <i class="fas fa-info-circle"></i>
                <p>暂无性别分布数据</p>
            </div>
        `;
        return table;
    }
    
    // 构建表格内容
    let tableHTML = `
        <div class="chart-header">
            <div class="chart-title">观众性别分布</div>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>性别</th>
                    <th>比例</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 遍历数据列表生成表格行
    dataList.forEach(item => {
        // 确保数据存在，避免NaN
    	let gender = item.gender || '未知';
    	let percentage = (item.percentage || 0).toFixed(1); // 保留一位小数
        
        tableHTML += `
            <tr>
                <td>${gender}</td>
                <td>${percentage}%</td>
            </tr>
        `;
    });
    
    tableHTML += `
            </tbody>
        </table>
    `;
    
    table.innerHTML = tableHTML;
    return table;
}
function createAgeDistributionTable(dataList) {
	let table = document.createElement('div');
    table.className = 'chart-card';
    
    // 检查数据是否存在
    if (!dataList || dataList.length === 0) {
        table.innerHTML = `
            <div class="chart-header">
                <div class="chart-title">观众年龄分布</div>
            </div>
            <div class="empty-data">
                <i class="fas fa-info-circle"></i>
                <p>暂无年龄分布数据</p>
            </div>
        `;
        return table;
    }
    
    // 构建表格内容
    let tableHTML = `
        <div class="chart-header">
            <div class="chart-title">观众年龄分布</div>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>年龄区间</th>
                    <th>比例</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 按 ageGroup 字段排序（确保顺序正确）
    let sortedData = [...dataList].sort((a, b) => {
        // 自定义排序逻辑：将 "41+" 放在最后
        if (a.ageGroup === "41+") return 1;
        if (b.ageGroup === "41+") return -1;
        
        // 对其他区间按数字顺序排序
        let aStart = parseInt(a.ageGroup.split("-")[0]);
        let bStart = parseInt(b.ageGroup.split("-")[0]);
        return aStart - bStart;
    });
    
    // 遍历数据生成表格行
    sortedData.forEach(item => {
        // 确保数据存在，避免NaN
    	let ageGroup = item.ageGroup || '未知';
    	let percentage = (item.percentage || 0).toFixed(1); // 保留一位小数
        
        tableHTML += `
            <tr>
                <td>${ageGroup}</td>
                <td>${percentage}%</td>
            </tr>
        `;
    });
    
    tableHTML += `
            </tbody>
        </table>
    `;
    
    table.innerHTML = tableHTML;
    return table;
}
function createDetailedDataTable(dataArray) {
    let table = document.createElement('div');
    table.className = 'chart-card';
    
    // 初始化表格结构
    let tableHTML = `
        <div class="chart-header">
            <div class="chart-title">详细数据统计</div>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>日期</th>
                    <th>播放量</th>
                    <th>新增粉丝</th>
                    <th>评论数</th>
                    <th>点赞数</th>
                    <th>分享数</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 检查数据是否存在
    if (dataArray && dataArray.length > 0) {
        // 遍历数据生成表格行
        dataArray.forEach(item => {
            // 格式化日期（从 "YYYY-MM-DD" 转为 "MM-DD"）
            let date = new Date(item.date);
            let month = (date.getMonth() + 1).toString().padStart(2, '0');
            let day = date.getDate().toString().padStart(2, '0');
            let formattedDate = `${month}-${day}`;
            
            // 获取各项数据（添加安全检查）
            let playCount = (item.playCount || 0).toLocaleString();
            let newFans = (item.newFans || 0).toLocaleString();
            let commentCount = (item.commentCount || 0).toLocaleString();
            let likeCount = (item.likeCount || 0).toLocaleString();
            let shareCount = (item.shareCount || 0).toLocaleString();
            
            // 添加表格行
            tableHTML += `
                <tr>
                    <td>${formattedDate}</td>
                    <td>${playCount}</td>
                    <td>${newFans}</td>
                    <td>${commentCount}</td>
                    <td>${likeCount}</td>
                    <td>${shareCount}</td>
                </tr>
            `;
        });
    } else {
        // 数据为空时显示空状态
        tableHTML += `
            <tr>
                <td colspan="6" class="empty-data">暂无数据</td>
            </tr>
        `;
    }
    
    // 完成表格结构
    tableHTML += `
            </tbody>
        </table>
    `;
    
    table.innerHTML = tableHTML;
    return table;
}
